# -*- coding: utf-8 -*-

"""
Time    :2021/6/15 下午9:41
Author  :chenyang
Email   :chenyang.it@outlook.com
FileName: devices.py
Software: PyCharm
"""
from flask import Blueprint, render_template, request, jsonify, redirect, url_for, g, session
from app.models import Devices, Admin
from app.extensions import db
from app.forms import AddDevice, Login
from .decorators import login_required

# 管理后台蓝图
admin = Blueprint('admin', __name__, url_prefix='/admin')


# 管理端展示
@admin.route('/')
@login_required
def index():
    devices = Devices.query.all()
    return render_template('admin.html', data=devices)


# 添加新设备
@admin.route('/add_device', methods=['GET', 'POST'])
@login_required
def add_device():
    if request.method == 'GET':
        return render_template('add_device.html')
    else:
        form = AddDevice(request.form)
        if form.validate():
            serialnumber = form.serialnumber.data
            model = form.model.data
            cpu_model = form.cpu_model.data
            cpu_cores = form.cpu_cores.data
            bmc_address = form.bmc_address.data
            purpose = form.purpose.data
            owner = form.owner.data
            others = form.others.data
            device = Devices.query.filter_by(sid=serialnumber).first()
            if not device:
                new_device = Devices(sid=serialnumber, model=model, cpu_model=cpu_model, cpu_cores=cpu_cores,
                                     bmc_address=bmc_address, purpose=purpose, owner=owner, others=others)
                db.session.add(new_device)
                db.session.commit()
                if Devices.query.filter_by(sid=serialnumber).first():
                    data = {
                        'code': 200,
                        'message': '设备添加成功。'
                    }
                    return jsonify(data)
                data = {
                    'code': 400,
                    'message': '设备添加失败！'
                }
                return jsonify(data)
            data = {
                'code': 400,
                'message': '设备已经存在！'
            }
            return jsonify(data)
        else:
            print(form.errors)
            data = {
                'code': 400,
                'message': form.errors
            }
            return jsonify(data)


# 删除设备
@admin.route('/del_device', methods=['POST'])
@login_required
def del_device():
    serialnumber = request.form.get('serialnumber')
    device = Devices.query.filter_by(sid=serialnumber).first()
    db.session.delete(device)
    db.session.commit()
    if not Devices.query.filter_by(sid=serialnumber).first():
        data = {
            'code': 200,
            'message': '设备删除成功'
        }
        return jsonify(data)


# 编辑设备
@admin.route('/edit_device', methods=['GET', 'POST'])
@login_required
def edit_device():
    if request.method == 'GET':
        serialnumber = request.args.get('serialnumber')
        # model = request.args.get('model')
        # cpu_model = request.args.get('cpu_model')
        # cpu_cores = request.args.get('cpu_cores')
        device = Devices.query.filter_by(sid=serialnumber).first()
        data = {
            'serialnumber': device.sid,
            'model': device.model,
            'cpu_model': device.cpu_model,
            'cpu_cores': device.cpu_cores,
            'bmc_address': device.bmc_address,
            'purpose': device.purpose,
            'owner': device.owner,
            'others': device.others
        }
        return render_template('edit_device.html', data=data)
    else:
        serialnumber = request.form.get('serialnumber')
        model = request.form.get('model')
        cpu_model = request.form.get('cpu_model')
        cpu_cores = request.form.get('cpu_cores')
        bmc_address = request.form.get('bmc_address')
        purpose = request.form.get('purpose')
        owner = request.form.get('owner')
        others = request.form.get('others')
        # print(serialnumber, model, cpu_model, cpu_cores, bmc_address, owner)
        device = Devices.query.filter_by(sid=serialnumber).first()
        device.model = model
        device.cpu_model = cpu_model
        device.cpu_cores = cpu_cores
        device.bmc_address = bmc_address
        device.purpose = purpose
        device.owner = owner
        device.others = others
        db.session.commit()

        data = {
            'code': 200,
            'message': '修改成功'
        }
        return jsonify(data)


# 管理员登录
@admin.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    else:
        form = Login(request.form)
        if form.validate():
            username = form.username.data
            password = form.password.data
            user = Admin.query.filter_by(name=username).first()
            if not user or not user.check_password(password):
                data = {
                    'code': 401,
                    'message': '用户名或密码错误！！！'
                }
                return jsonify(data)
            # 用户名密码正确
            session['uid'] = user.uid
            data = {
                'code': 200,
                'message': 'OK'
            }
            return jsonify(data)
        else:
            error_list = []
            for value in form.errors.values():
                error_list.append(value[0])
            data = {
                'code': 401,
                'message': error_list[0]
            }
            return jsonify(data)


# 管理员登录
@admin.route('/logout')
def logout():
    session.pop('uid')
    if not session.get('uid'):
        return jsonify({
            'code': 200,
            'message': 'OK'
        })
